package com.mmx.baseservice.common.swagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class SwaggerConfig {
	/**
	 * 通过 createRestApi函数来构建一个DocketBean 函数名,可以随意命名,喜欢什么命名就什么命名
	 */
	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2)
				//添加登录认证
				.securitySchemes(securitySchemes())
				.securityContexts(securityContexts())
				.apiInfo(apiInfo())
				// 调用apiInfo方法,创建一个ApiInfo实例,里面是展示在文档页面信息内容
				.select()
				// 控制暴露出去的路径下的实例
				// 如果某个接口不想暴露,可以使用以下注解
				// @ApiIgnore 这样,该接口就不会暴露在 swagger2 的页面下
				.apis(RequestHandlerSelectors.basePackage("com.mmx"))
				.paths(PathSelectors.any()).build();
				
	}

	/**
	 * 构建 api文档的详细信息函数
	 * @return
	 */
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				// 页面标题
				.title("基础架构系统  API")
				// 版本号
				.version("1.0")
				// 描述
				.description("基础架构系统 API").build();
	}

	 /**
     * 设置token请求头
     * @return
     */
    private List<SecurityScheme> securitySchemes(){
		//设置请求头信息
		List<SecurityScheme> result = new ArrayList<>();
		ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");
		result.add(apiKey);
		return result;
    }

	private List<SecurityContext> securityContexts() {
		//设置需要登录认证的路径
		List<SecurityContext> result = new ArrayList<>();
		result.add(getContextByPath());
		return result;
	}

	private SecurityContext getContextByPath() {
		return SecurityContext.builder()
				.securityReferences(defaultAuth())
				.forPaths(PathSelectors.regex(".*"))
				.build();
	}

	private List<SecurityReference> defaultAuth() {
		List<SecurityReference> result = new ArrayList<>();
		AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
		AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
		authorizationScopes[0] = authorizationScope;
		result.add(new SecurityReference("Authorization", authorizationScopes));
		return result;
	}


}
